#include "lua_f_base.h"
#include <cutils/io_base.h>

static int lua_f_io_client_read(lua_State *L)
{
	io_client_t *cli = (io_client_t *)lua_touserdata(L, 1);
	if (!cli)
		RETERR("invalid light userdata");
	
	if (cli->in_len == 0) {
		lua_pushnil(L);
		return 1;
	}

	lua_pushlstring(L, (const char *)cli->in_buf, cli->in_len);
	cli->in_len = 0;
	return 1;
}

static int lua_f_io_client_write(lua_State *L)
{
	int n = lua_gettop(L);

	io_client_t *cli = (io_client_t *)lua_touserdata(L, 1);
	if (!cli)
		RETERR("invalid light userdata");

	if (n < 2) {
		io_client_write(cli, NULL, 0);
		lua_pushinteger(L, 0);
		return 1;
	}

	size_t len = 0;
	const char *data = lua_tolstring(L, 2, &len);
	DBG("len = %u", len);
	if (len == 0)
		goto _out;

	if (io_client_write(cli, (uint8_t *)data, len) < 0)
		RETERR("io_client_write fail");
	
_out:
	lua_pushinteger(L, len);
	return 1;
}

static int lua_f_io_client_term(lua_State *L)
{
	io_client_t *cli = (io_client_t *)lua_touserdata(L, 1);
	if (!cli)
		RETERR("invalid light userdata");

	io_client_put(cli);
	return 0;
}

static int lua_f_io_client_version(lua_State *L)
{
	const char *ver = "IOClient V0.0.1";
	lua_pushstring(L, ver);
	return 1;
}

static const struct luaL_Reg lua_f_io_client_mod[] = {
	{"term", lua_f_io_client_term},
	{"read", lua_f_io_client_read},
	{"write", lua_f_io_client_write},
	{"version", lua_f_io_client_version},
	{NULL, NULL},
};


int luaopen_io_client(lua_State *L)
{
	luaL_register(L, "io_client", lua_f_io_client_mod);
	return 1;
}
